package com.leetcode.algorithm.y22.m06;

/**
 * 1790. 仅执行一次字符串交换能否使两个字符串相等
 * 
 * https://leetcode.cn/problems/check-if-one-string-swap-can-make-strings-equal/
 * 
 * @author jie.deng
 *
 */
class Question1790Solution01 {

	public boolean areAlmostEqual(String s1, String s2) {
		int len = s1.length();
		int firstDiffIdx = -1;
		int secondDiffIdx = -1;
		int idx = 0;
		while (idx < len && s1.charAt(idx) == s2.charAt(idx)) {
			idx++;
		}
		if (idx == len) {
			// s1和s2相等
			return true;
		} else {
			firstDiffIdx = idx;
			idx++;
		}

		while (idx < len && s1.charAt(idx) == s2.charAt(idx)) {
			idx++;
		}
		if (idx == len) {
			// s1和s2仅有一个字符有差异
			return false;
		} else {
			secondDiffIdx = idx;
			idx++;
		}
		if (s1.charAt(firstDiffIdx) != s2.charAt(secondDiffIdx)
				|| s2.charAt(firstDiffIdx) != s1.charAt(secondDiffIdx)) {
			// 交换不相等
			return false;
		}

		while (idx < len && s1.charAt(idx) == s2.charAt(idx)) {
			idx++;
		}
		return idx == len;
	}

}